package com.lagou.product.controller;

import com.lagou.common.pojo.Product;
import com.lagou.common.service.ProductService;
import com.lagou.common.utils.KafkaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @BelongProject: task9-2
 * @author: 胡恺恺
 * @createTime: 2021/2/5  12:15
 * @Description:
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    public static String KAFKA_TOPIC = "product";

    @Autowired
    private ProductService productService;

    /**
     * 插入商品
     * @param product
     * @return
     */
    @PostMapping("/insert")
    public String insert(@RequestBody Product product) {
        //1.持久化商品到数据库
        int result =  productService.insertProduct(product);
        String msg = (result == 1) ? "添加成功!" : "添加失败!";
        //向Kafka集群发送消息
        //2、生产消息：商品微服务将商品对象保存后，获得该商品对象在数据库中记录的id，将该id作为消息发送到Kafka的product主题中
        KafkaUtils.sendMessage("product",String.valueOf(product.getId()));

        return msg;
    }

    /**
     * 根据id查询商品
     * @param id
     * @return
     */
    @GetMapping("/query/{id}")
    public Product insert(@PathVariable("id") Integer id) {
        return productService.queryById(id);
    }
}
